package com.yc.thread;

/**
 * @program: concurrent
 * @description: 精灵线程   其它线程运行，精灵线程也会结束.
 * @author: zy
 * @create: 2022-01-10 11:19
 */
public class Test9_daemon {
    public static void main(String[] args) {
        Thread t1 = new CommonThread();
        t1.setDaemon(true);
        //新建任务，再绑定到一个线程上.
        Thread t2 = new Thread(new MyDaemon());
        //TODO: 设置为守护线程
        t2.setDaemon(true);
        // 正确做法：线程运行前设置守护线程
        t2.start();
        t1.start();

        System.out.println("主程序已经运行完了");
    }
}
//线程
class CommonThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("用户线程第" + i + "次执行！");
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
//任务类
class MyDaemon implements Runnable {
    @Override
    public void run() {
        for (long i = 0; i < 20; i++) {
            System.out.println("守护线程第" + i + "次执行！");
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
